package com.smart.sso.server.switchdb;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.smart.sso.server.model.NodeDB;
import com.smart.sso.server.service.NodeDBService;
/**
 * 切面类
 * @author Administrator
 *
 */
@Aspect
@Component
@Order(1)
public class DataSourceInterceptor {
	
	@Resource
	private NodeDBService nodeDBService;
	
	public DataSourceInterceptor() {
		// TODO Auto-generated constructor stub
	}
	
//	@Pointcut("execution(* com.smart.sso.server.service.GroupService.findPaginationByName(..))")
	@Pointcut("execution(* com.smart.sso.server.service.*.*(..)) || execution(* com.smart.mvc.service.mybatis.*.*(..))")
	public void dataSourceSlave(){};
	    
    @Before("dataSourceSlave()")
    public void before(JoinPoint jp) {
    	DynamicDataSource dataSource = (DynamicDataSource) SpringContextUtil.getBean("dataSource");
    	HttpSession session = SessionContainer.getSession();
    	
    	if(session.getAttribute("NODE_KEY")==null)
    		return;
    	
    	String nodeKey = (String) session.getAttribute("NODE_KEY");
    	if(nodeKey.equals(""))
    		return;
    	if(nodeKey.equals("MASTER")) {
    		dataSource.cleanDatasources();
    		DBContextHolder.setDataSource(nodeKey);
    		return;
    	}
    	
    	if(dataSource.getDynamicTargetDataSources().containsKey(nodeKey)) {
    		DBContextHolder.setDataSource(nodeKey);	//该数据源已存在，将其设为目标数据源
    		return;
    	}
    	
    	/******	创建新数据源，并切换	****************/
    	dataSource.cleanDatasources();
    	NodeDB nodeDB = (NodeDB) session.getAttribute("CURRENT_NODE");
    	dataSource.createDataSource(nodeKey, nodeDB.getDriver(), nodeDB.getUrl(), nodeDB.getAdminName(), nodeDB.getPassword());
    	DBContextHolder.setDataSource(nodeKey);	//切换到新数据源
    }
}
